﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;
using System.IO;
using BUS;
using DTO;
using System.Text;
namespace Cucre
{
    public partial class WebForm6 : System.Web.UI.Page
    {
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            string path = Server.MapPath("theme.txt");
            StreamReader SR = new StreamReader(path);
            string nameTheme = SR.ReadLine();
            SR.Close();
            base.OnPreInit(e);
            if (Session["MyTheme"] == null)
            {
                Session.Add("MyTheme", nameTheme);
                Page.Theme = (string)Session["MyTheme"];
            }
            else
            {
                Page.Theme = (string)Session["MyTheme"];
            }
        }
        public string readFileTxt(string fname)
        {
            string s = System.IO.File.ReadAllText(fname);
            return s;
        }
        public List<PRODUCT> listProducts;
        public List<COMMENT> listComments;
        public double TongGia = 0;
        public MEMBER member = null;
        public ACCOUNT account = new ACCOUNT();
        public PRODUCT SanPham = new PRODUCT();

        private int ReadComment(int idSanPham)
        {
            listComments.Clear();
            listComments = CommentBUS.GetComment(idSanPham);
            if (listComments == null)
                return -1;
            return listComments.Count;
        }
        protected void Mua_Click(object sender, EventArgs e)
        {
            ORDER order = new ORDER();
            if (account != null)
            {
                try
                {
                    member = MemberBUS.getMember(account.IDACCOUNT);
                    order.IDMEMBER = member.IDMEMBER;
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('BẠN KHÔNG CÓ QUYỀN MUA HÀNG')", true);
                    return;
                }
            }
            else
            {
                if (HoTen.Text == "")
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Điền vào họ tên của bạn')", true);
                    errorHoTen.Visible = true;
                }
                else
                    if (Email.Text == "")
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Điền vào email của bạn')", true);
                        errorHoTen.Visible = false;
                        errorEmail.Visible = true;
                    }
                    else
                        if (DienThoai.Text == "")
                        {
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Điền vào điện thoại của bạn')", true);
                            errorEmail.Visible = false;
                            errorDienThoai.Visible = true;
                        }
                        else
                            if (DiaChi.Text == "")
                            {
                                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Điền vào địa chỉ của bạn')", true);
                                errorDienThoai.Visible = false;
                                errorDiaChi.Visible = true;
                            }
                            else
                            {
                                MEMBER newMember = new MEMBER();
                                newMember.ACCOUNT = new ACCOUNT();
                                newMember.ACCOUNT.ADDRESS = DiaChi.Text;
                                newMember.ACCOUNT.EMAIL = Email.Text;
                                newMember.ACCOUNT.FULLNAME = HoTen.Text;
                                newMember.ACCOUNT.USERNAME = "guest" + MemberBUS.GetIDMax().ToString();
                                newMember.ACCOUNT.PASSWORD = "";
                                newMember.ACCOUNT.PHONE_NUMBER = DienThoai.Text;
                                MemberBUS.insertMember(newMember);
                                int idMember = MemberBUS.GetIDMax();
                                order.IDMEMBER = idMember;
                            }
            }
            order.IDPRODUCT = SanPham.IDPRODUCT;

            order.PAYMENT = 0;
            if (Request.Form["quantity"].ToString() == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Bạn chưa chọn số lượng sản phẩm')", true);
            }
            order.QUANTITY = byte.Parse(Request.Form["quantity"].ToString());
            SanPham.OrderedNumber += order.QUANTITY;
            ProductBUS.Update(SanPham);
            order.STATUS_ORDER = 2;
            order.TIME_ORDER = DateTime.Now;
            OrderBUS.insertoOrder(order);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Bạn đã mua hàng thành công. Chúng tôi sẽ liên hệ với bạn');window.location.href='"+Request.Url.ToString()+"'", true);
        }


        public void ShowComment()
        {
            List<COMMENT> ListComment = new List<COMMENT>();
            ListComment = CommentBUS.GetComment(SanPham.IDPRODUCT);
            comment.Controls.Clear();
            if (ListComment == null)
                return;
            for (int i = 0; i < ListComment.Count; ++i)
            {
                Label la = new Label();
                la.Text = "<div style='height:20px;margin-left: 25px' align='left' > " + "Được Gửi Bởi : " + ListComment[i].ACCOUNT.USERNAME + "<br/>         Vào lúc : " + ListComment[i].TIME_COMMENT.Value.ToString() + "</div><br/>";
                comment.Controls.Add(la);
                HtmlTextArea h = new HtmlTextArea();
                h.Value = ListComment[i].CONTENT;
                h.ID = ListComment[i].IDCOMMENT.ToString();
                h.Style.Value = "width:600px";
                h.Disabled = true;
                comment.Controls.Add(h);
                Label labr = new Label();
                labr.Text = "<br/><br/>";
                comment.Controls.Add(labr);
            }
        }

        protected void SubmitComment_Click(object sender, EventArgs e)
        {
            if (account != null)
            {
                if (TextBox1.Text.Trim() == "")
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Comment không có nội dung !!!. Vui lòng kiểm tra lại')", true);
                }
                COMMENT comm = new COMMENT();
                comm.IDACCOUNT = account.IDACCOUNT;
                comm.IDPRODUCT = SanPham.IDPRODUCT;
                comm.TIME_COMMENT = DateTime.Now;
                comm.CONTENT = TextBox1.Text.Trim();
                TextBox1.Text = "";
                CommentBUS.Insert(comm);
                ShowComment();
            }
            else
                if (account == null)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Bạn đăng nhập vào hệ thống !!!. Vui lòng đăng nhập để tiếp tục comment')", true);
                }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string account_style = (string)Session["user_style"];

            if (account_style == "4")
            {
                PROVIDER provider = (PROVIDER)Session["user_login"];
                account = provider.ACCOUNT;
            }
            else
                if (account_style == "1" || account_style == "2" || account_style == "3")
                {
                    MEMBER member = (MEMBER)Session["user_login"];
                    account = member.ACCOUNT;
                }
                else
                    account = null;

            int IDSanPham;
            try
            {
                IDSanPham = int.Parse(Request.Params["IDSanPham"]);
            }
            catch
            {
                IDSanPham = -1;
            }
            if (IDSanPham != -1)
            {
                SanPham = ProductBUS.GetProduct(IDSanPham);
                Session.Add("SanPhamHienTai", SanPham);
                listProducts = new List<PRODUCT>();
                listComments = new List<COMMENT>();
                listProducts = ProductBUS.GetAllProduct();
                ShowComment();
                lbCity.Text = SanPham.CITY.Trim() + ": ";
                lbSlogan.Text = SanPham.SLOGAN + ".";
                lbGiaGiam.Text = "<font style='font-size:30px'>" + SanPham.RATE_DECREASE + "%" + "</font>";
                lbDiaChi.Text = SanPham.PROVIDER.ACCOUNT.ADDRESS + " ";
                lbSDT.Text = SanPham.PROVIDER.ACCOUNT.PHONE_NUMBER;
                lbGia.Text = "<font style='font-size:25px'>" + String.Format("{0:0,0}", SanPham.PRICE) + "</font>";
                double giaGoc = Math.Round((double)(SanPham.PRICE * 100 / (100 - SanPham.RATE_DECREASE)), 0);
                lbGiaGoc.Text = String.Format("{0:0,0}", giaGoc);
                lbGiamGia.Text = SanPham.RATE_DECREASE.ToString() + " % ";
                lbGiaTietKiem.Text = String.Format("{0:0,0}", giaGoc - SanPham.PRICE);
                string dayNumber = (SanPham.TIME_STOP.Value.Subtract(DateTime.Now)).TotalSeconds.ToString();



                StringBuilder sb = new StringBuilder();
                sb.Append("<script language='JavaScript'>");
                sb.AppendFormat("clock_time_remain['265'] = " + dayNumber + ";");
                sb.Append("</script>");
                Page.RegisterStartupScript("Test", sb.ToString());

                //Đoạn script kích hoạt Slide chạy
                string soPhieuConLai = (((SanPham.MAX_NUMBER - SanPham.OrderedNumber) * 182) / SanPham.MAX_NUMBER).ToString();
                string soNguoiDaThanhToan = ((SanPham.PurchasedNumber * 182) / SanPham.MAX_NUMBER).ToString();
                StringBuilder sb1 = new StringBuilder();
                sb1.Append("<script language='JavaScript'>");
                sb1.AppendFormat("document.getElementById('SlideDaThanhToan').style.width='" + soNguoiDaThanhToan + "px';document.getElementById('SlideSoPhieuConLai').style.width='" + soPhieuConLai + "px';");
                sb1.Append("</script>");
                Page.RegisterStartupScript("Test1", sb1.ToString());

                //
                TongGia = double.Parse((SanPham.PRICE - (SanPham.PRICE * SanPham.RATE_DECREASE / 100)).ToString());

                StringBuilder sb2 = new StringBuilder();
                sb2.Append("<script language='JavaScript'>");
                sb2.AppendFormat("var real_phagia_price  = " + SanPham.PRICE + ";");
                sb2.Append("</script>");
                Page.RegisterStartupScript("Test2", sb2.ToString());

                StringBuilder sb3 = new StringBuilder();
                sb3.Append("<script language='JavaScript'>");
                sb3.AppendFormat("document.getElementById('Tong').innerHTML = " + SanPham.PRICE + ";");
                sb3.Append("</script>");
                Page.RegisterStartupScript("Test3", sb3.ToString());

                lbNgayHetHan.Text = string.Format("{0:dd/MM/yyyy}", SanPham.TIME_STOP.Value);
                lbSoPhieuToiDa.Text = SanPham.MAX_NUMBER.ToString();
                lbSoPhieuToiDa2.Text = SanPham.MAX_NUMBER.ToString();
                lbSoPhieuDatMua.Text = SanPham.OrderedNumber.ToString();
                lbSoPhieuDaThanhToan.Text = SanPham.PurchasedNumber.ToString();
                lbSoPhieuConLai.Text = (SanPham.MAX_NUMBER - SanPham.OrderedNumber).ToString();
                lbDieuKienApDung.Text = SanPham.Conditions_Apply;// readFileTxt("Cucre/" + SanPham.Conditions_Apply);
                lbDacDiemNoiBat.Text = SanPham.Features;// readFileTxt("Cucre/" + SanPham.Features);
                //show_image_chinh_265.ImageUrl = @"~\" + SanPham.IMAGE;
                linkChiTiet.NavigateUrl = "chitietsanpham.aspx?IDSanPham=" + SanPham.IDPRODUCT.ToString();
                linkBanDo.NavigateUrl = "bando.aspx?IDSanPham=" + SanPham.IDPRODUCT.ToString();
                linkSlogan.NavigateUrl = "chitietsanpham.aspx?IDSanPham=" + SanPham.IDPRODUCT.ToString();
                lbVungChiTiet.Text = SanPham.CONTENT;// readFileTxt("Cucre/" + SanPham.CONTENT);
                lbThongTinDoanhNghiep.Text = SanPham.PROVIDER.INTRODUCE_COMPANY;// readFileTxt("Cucre/" + SanPham.Features);
                Image1.ImageUrl = @"~\" + SanPham.IMAGE + "1.jpg";
                Image2.ImageUrl = @"~\" + SanPham.IMAGE + "2.jpg";
                Image3.ImageUrl = @"~\" + SanPham.IMAGE + "3.jpg";
                Image4.ImageUrl = @"~\" + SanPham.IMAGE + "4.jpg";
                Image5.ImageUrl = @"~\" + SanPham.IMAGE + "5.jpg";


                MaSP.Text = SanPham.IDPRODUCT.ToString();
                TenSP.Text = SanPham.Name_Product;
                GiaSP.Text = String.Format("{0:0,0}", giaGoc);
                Giam.Text = SanPham.RATE_DECREASE.ToString() + "%";
                GiaSauGiam.Text = String.Format("{0:0,0}", SanPham.PRICE);

                if (account != null)
                {
                    HoTen.Text = account.FULLNAME;
                    HoTen.Enabled = false;
                    Email.Text = account.EMAIL;
                    HoTen.Enabled = false;
                    DienThoai.Text = account.PHONE_NUMBER;
                    DiaChi.Text = account.ADDRESS;
                    Ghichu.Text = "";
                }
            }
        }
    }
}